package com.jy.oms.framework.template;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.util.Map;

/**
 * 模板服务
 *
 * @author liuquan
 */
public class TemplateService {
    private static final Logger logger = LoggerFactory.getLogger(TemplateService.class);
    private static TemplateService INSTANCE = new TemplateService();
    private Configuration configuration;
    private StringTemplateLoader stringTemplateLoader;

    private TemplateService() {
        try {
            configuration = new Configuration(Configuration.VERSION_2_3_28);
            stringTemplateLoader = new StringTemplateLoader();
            configuration.setTemplateLoader(stringTemplateLoader);
            configuration.setDefaultEncoding("UTF-8");
            configuration.setNumberFormat("#.####");
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        } catch (Exception e) {
        }
    }

    public static TemplateService getInstance() {
        return INSTANCE;
    }

    public void putTemplate(String templateKey, String templateContent) {
        if (stringTemplateLoader == null) {
            logger.error("模板服务初始化错误，请检查是否引入freemarker_2.3.28依赖配置");
            return;
        }

        stringTemplateLoader.putTemplate(templateKey, templateContent);
    }

    public String getTemplateContent(String templateKey, Map<String, Object> param) {
        if (stringTemplateLoader == null) {
            logger.error("模板服务初始化错误，请检查是否引入freemarker_2.3.28依赖配置");
            return null;
        }

        try {
            Template template = configuration.getTemplate(templateKey);
            StringWriter writer = new StringWriter();
            template.process(param, writer);
            return writer.toString();
        } catch (Exception e) {
            logger.error("获取模板内容报错", e);
        }

        return null;
    }
}
